package com.yunbiao.ybbusstopplate.refactoring.ui.fengxian;

import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.UiMessageUtils;
import com.yunbiao.ybbusstopplate.R;
import com.yunbiao.ybbusstopplate.base.BaseFragment;
import com.yunbiao.ybbusstopplate.base.BaseSettingFragment;
import com.yunbiao.ybbusstopplate.databinding.FragmentFengxianNodeSiteBinding;
import com.yunbiao.ybbusstopplate.refactoring.Config;
import com.yunbiao.ybbusstopplate.refactoring.ui.dalian.ZHIDAParser;
import com.yunbiao.ybbusstopplate.refactoring.serial.SerialPortServices;
import com.yunbiao.ybbusstopplate.refactoring.ui.adapter.UpSiteAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

public class FengxianNodeSiteFragment extends BaseFragment{

    private FragmentFengxianNodeSiteBinding binding;

    @Override
    public int getViewId() {
        return R.layout.fragment_fengxian_node_site;
    }

    @Override
    protected void initView(){
        binding = DataBindingUtil.bind(requireView());

        if(Config.getAgreement().equals(Config.Agreement.BASHITONG)){
            binding.tvLineName.setBackgroundResource(android.R.color.holo_green_dark);
            binding.clInformation.setBackgroundResource(android.R.color.holo_green_dark);
        }

        UiMessageUtils.getInstance().addListener(ZHIDAParser.Event.UPDATE_LINE_NAME.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().addListener(ZHIDAParser.Event.UPDATE_SITE_LIST.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().addListener(ZHIDAParser.Event.BROAD_SITE.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().addListener(ZHIDAParser.Event.UPDATE_START_END.getType(),uiMessageCallback);

        binding.rlvList.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false){
            @Override
            public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
                RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(recyclerView.getContext()){
                    @Override
                    public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
                        return (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2);
                    }
                };
                smoothScroller.setTargetPosition(position);
                startSmoothScroll(smoothScroller);
            }
        });
//        binding.rlvList.addItemDecoration(new RecyclerView.ItemDecoration() {
//            @Override
//            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
//                super.getItemOffsets(outRect, view, parent, state);
//                Log.d(TAG, "getItemOffsets: 11111111111111111");
//            }
//
//            @Override
//            public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
//                super.onDraw(c, parent, state);
//                Log.d(TAG, "onDraw: 222222222222222222222");
//
//                LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
//                if(layoutManager != null){
//                    int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
//                    View childAt = layoutManager.getChildAt(0);
//                    if(childAt != null){
//                        int position = layoutManager.getPosition(childAt);
//
//                        Log.d(TAG, "onDraw: " + firstVisibleItemPosition + " --- " + position);
//                    }
//                }
//            }
//
//            @Override
//            public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
//                super.onDrawOver(c, parent, state);
//                Log.d(TAG, "onDrawOver: 3333333333333333333");
//            }
//        });

        binding.vSetting.setOnClickListener(v -> {
            FragmentUtils.add(getChildFragmentManager(),new FengxianSettingFragment(),binding.flSetting.getId());
        });

        binding.vLog.setOnClickListener(v -> {
            FragmentUtils.add(getChildFragmentManager(),new RefactoringLogFragment(),binding.flSetting.getId());
        });
    }

    @Override
    public void initData() {
        SerialPortServices.start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        SerialPortServices.stop();
        EventBus.getDefault().unregister(this);
        UiMessageUtils.getInstance().removeListener(ZHIDAParser.Event.UPDATE_LINE_NAME.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().removeListener(ZHIDAParser.Event.UPDATE_SITE_LIST.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().removeListener(ZHIDAParser.Event.BROAD_SITE.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().removeListener(ZHIDAParser.Event.UPDATE_START_END.getType(),uiMessageCallback);
    }

    private static final String TAG = "NodeSiteFragment";
    private final UiMessageUtils.UiMessageCallback uiMessageCallback = uiMessage -> {
        int id = uiMessage.getId();
        Object object = uiMessage.getObject();
        if(id == ZHIDAParser.Event.UPDATE_LINE_NAME.getType()){
            if(object instanceof String){
                binding.tvLineName.setText(object.toString());
            }
        } else if(id == ZHIDAParser.Event.UPDATE_SITE_LIST.getType()){
            ZHIDAParser.Site[] sites = (ZHIDAParser.Site[]) object;
            if(sites != null && sites.length > 0){
                setSiteData(sites);
            }
        } else if(id == ZHIDAParser.Event.BROAD_SITE.getType()){
            Object[] objects = (Object[]) object;
            if(objects != null && objects.length > 1){
                ZHIDAParser.Site site = (ZHIDAParser.Site) objects[0];

                UpSiteAdapter adapter = (UpSiteAdapter) binding.rlvList.getAdapter();
                if(adapter != null){
                    adapter.setCurrPosition(site.getIndex());

                    int positionOfIndex = adapter.getPositionOfIndex(site.getIndex());
                    binding.rlvList.smoothScrollToPosition(positionOfIndex);
                }
            }
        } else if(id == ZHIDAParser.Event.UPDATE_START_END.getType()){
            String[] strings = (String[]) object;

            String upStartEndSite = strings[0];
            String upStartTime = "";
            if(strings.length >= 3){
                upStartTime = strings[2];
            }
            String upEndTime = "";
            if(strings.length >= 4){
                upEndTime = strings[3];
            }

            String downStartEndSite = strings[1];
            String downStartTime = "";
            if(strings.length >= 5){
                downStartTime = strings[4];
            }
            String downEndTime = "";
            if(strings.length >= 6){
                downEndTime = strings[5];
            }

            if(TextUtils.isEmpty(upStartEndSite)){
                binding.tvUpStartEnd.setVisibility(View.INVISIBLE);
                binding.llUpStartEndTime.setVisibility(View.INVISIBLE);
            } else {
                binding.tvUpStartEnd.setVisibility(View.VISIBLE);
                binding.llUpStartEndTime.setVisibility(View.VISIBLE);
                binding.tvUpStartEnd.setText(upStartEndSite);
                binding.tvUpStartTime.setText(upStartTime);
                binding.tvUpEndTime.setText(upEndTime);
            }

            if(TextUtils.isEmpty(downStartEndSite)){
                binding.tvDownStartEnd.setVisibility(View.INVISIBLE);
                binding.llDownStartEndTime.setVisibility(View.INVISIBLE);
            } else {
                binding.tvDownStartEnd.setVisibility(View.VISIBLE);
                binding.llDownStartEndTime.setVisibility(View.VISIBLE);
                binding.tvDownStartEnd.setText(downStartEndSite);
                binding.tvDownStartTime.setText(downStartTime);
                binding.tvDownEndTime.setText(downEndTime);
            }
        }
    };
    private void setSiteData(ZHIDAParser.Site[] sites){
        final int spanCount = Math.min(sites.length, 25);

        UpSiteAdapter siteAdapter = (UpSiteAdapter) binding.rlvList.getAdapter();
        if(siteAdapter != null){
            binding.rlvList.setAdapter(null);
        }

        binding.rlvList.setAdapter(new UpSiteAdapter(sites){
            @NonNull
            @Override
            public Holder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                Holder holder = super.onCreateViewHolder(viewGroup, i);
                ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
                layoutParams.width = binding.rlvList.getWidth() / spanCount;
                holder.itemView.setLayoutParams(layoutParams);
                return holder;
            }
        });
    }

    private long mExitTime = 0;
    @Override
    public boolean onBackClick() {
        List<Fragment> fragments = FragmentUtils.getFragments(getChildFragmentManager());
        for (int i = fragments.size() - 1; i >= 0; i--) {
            Fragment fragment = fragments.get(i);
            if(fragment instanceof BaseSettingFragment){
                FragmentUtils.remove(fragment);
                return true;
            }
        }
        return false;
    }
}
